package com.buffer.agent.memory;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

// 会话记忆：存储用户与智能体的历史对话（Redis 实现）
@Component
public class SessionMemory {
    private final StringRedisTemplate redisTemplate;
    private static final String SESSION_KEY = "qwen:agent:session:";
    private static final int EXPIRE_HOURS = 24;  // 会话有效期 24 小时
    private static final int MAX_HISTORY = 10;   // 最多保留 10 轮对话
    
    public SessionMemory(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    // 保存对话历史
    public void saveHistory(String userId, String userMsg, String agentMsg) {
        String key = SESSION_KEY + userId;
        String historyItem = String.format("用户：%s | 智能体：%s", userMsg, agentMsg);
        // 左推到列表，保留最新 10 条
        redisTemplate.opsForList().leftPush(key, historyItem);
        redisTemplate.opsForList().trim(key, 0, MAX_HISTORY - 1);
        redisTemplate.expire(key, EXPIRE_HOURS, TimeUnit.HOURS);
    }
    
    // 获取对话历史（用于智能体参考上下文）
    public String getHistory(String userId) {
        String key = SESSION_KEY + userId;
        List<String> historyList = redisTemplate.opsForList().range(key, 0, -1);
        if (historyList == null || historyList.isEmpty()) {
            return "无历史对话";
        }
        StringBuilder sb = new StringBuilder("对话历史：\n");
        for (String item : historyList) {
            sb.append(item).append("\n");
        }
        return sb.toString();
    }
}
